<?php

namespace Coupon;

use C\L\AdmController;

class CouponController extends AdmController
{
    protected function init()
    {
        $this->service = $this->s_coupon;
        $this->likeSearchKeys = [
            'goods_title', 'status', 'use_condition_msg'
        ];

        $this->pubSearchKeys = [
            'cat'
        ];

        $this->hideKeys = [
            'is_delete'
        ];

        $this->timeToDateKeys = [
            'uptime', 'addtime', 'stime', 'etime'
        ];

        $this->updateKeys = [
            'coupon_value', 'coupon_type', 'use_condition', 'use_condition_msg',
            'goods_id', 'goods_title', 'stime', 'etime', 'payment_amount',
            'verifi_num', 'status'
        ];

        $this->createKeys = [
            'coupon_value', 'coupon_type', 'use_condition', 'use_condition_msg',
            'goods_id', 'goods_title', 'stime', 'etime', 'payment_amount',
        ];
    }

    protected function beforeSearch()
    {
        $type = $this->getValue('type', false, 'int');
        if (!empty($type) && !is_numeric($type)) {
            $this->error('参数错误');
        }
        $this->params['data']['type'] = $type ? $type : '1';
        return true;
    }

    protected function afterSearch(&$data)
    {
        $data['list'] = array_map(function ($item) {
            $item['released_count'] = $this->s_coupon_receive->getCount(['coupon_id' => $item['id']]);
            $item['used_count']     = $this->s_coupon_receive->getCount(['coupon_id' => $item['id'], 'status' => 'Y']);
            return $item;
        }, $data['list']);
        return true;
    }

    protected function beforeCreate(&$data)
    {
        $this->rule($data);
        return true;
    }

    protected function beforeRemove()
    {
        $id = $this->getValue('id', true, 'int');
        $res = $this->s_coupon->search(['id' => $id]);
        if (empty($res)) {
            $this->error('数据不存在');
        }
        return true;
    }

    protected function beforeUpdate(&$data)
    {
        $this->rule($data);
        return true;
    }

    public function rule(&$data)
    {
        $coupon_value = $this->getValue('coupon_value', true, 'int');
        $use_condition = $this->getValue('use_condition', false, 'int');
      // 优惠券面额不得大于使用门槛金额
        if (isset($use_condition) && $coupon_value >= $use_condition) {
            $this->error('优惠券面额大于使用门槛了');
        }
      // 存在；则是满减券，反之；是无门槛券
        if (isset($use_condition)) {
            $data['coupon_type'] = '1';
            $data['use_condition_msg'] = sprintf('单件商品满%s元可用', $use_condition);
        } else {
            $data['coupon_type'] = '2';
        }
      // 适用商品ID必须是整型，也限定了只能选一个
        $goods_id = $this->getValue('goods_id', true, 'int');
      // 有效开始时间不得早于当前时间
        $stime = $this->getValue('stime', true, 'string');
        $etime = $this->getValue('etime', true, 'string');
        $current_time = date('Y-m-d H:i:s');
        if ($current_time >= $stime) {
            $this->error('有效开始时间不得早于当前时间');
        }
        if ($stime >= $etime) {
            $this->error('有效开始时间不得大于等于有效结束时间');
        }
        $data['stime'] = strtotime($stime);
        $data['etime'] = strtotime($etime);
      // $payment_amount = $this->getValue('payment_amount', true, 'int');
    }

  /**
   * VIP代金券创建
   */
    public function vipVoucherCreateAction()
    {
        if (empty($this->uid)) {
            $this->error('非法访问');
        }
        $params = [];
        $coupon_value = $this->getValue('coupon_value', true, 'int');
        if (empty($coupon_value)) {
            $this->error('面额不能为空');
        }
        $params['coupon_value'] = $coupon_value;
        $use_condition = $this->getValue('use_condition', true, 'int');
        if (empty($use_condition)) {
            $this->error('使用条件不能为空');
        }
        $params['use_condition'] = $use_condition;
        $effective_time = $this->getValue('effective_time', true, 'int');
        if (empty($effective_time)) {
            $this->error("几日内可用不能为空");
        }
        $params['effective_time'] = $effective_time;
        $vip_name = $this->getValue('vip_name', true, 'string');
        $vip_name_arr = array_map(function ($value) {
            return $value['name'];
        }, $this->s_level->getVipNames());
        if (empty($vip_name) || !in_array($vip_name, $vip_name_arr)) {
            $this->error('vip_name非法');
        }
        $params['vip_name'] = $vip_name;
        $id = $this->getValue('id', false, 'int');
        if (!empty($id)) {
            $isUp = $this->s_coupon->search(['id' => $id, 'status' => 'N']);
            if (empty($isUp)) {
                $this->error('该券已发放，无法更改');
            }
            $params['id'] = $id;
        }
        if (!$this->s_coupon->checkConformUser($vip_name)) {
            $this->error('没有符合条件的用户');
        }
        if ($res = $this->s_coupon->createVipVoucher($params)) {
            $this->success($res);
        }
        $this->error();
    }

    public function getVipListAction()
    {
        if (empty($this->uid)) {
            $this->error('非法访问');
        }
        if ($res = $this->s_level->getVipNames()) {
            $this->success($res);
        }
        $this->error();
    }

  /**
   * VIP代金券回显
   */
    public function vipVoucherViewAction()
    {
        if (empty($this->uid)) {
            $this->error('非法访问');
        }
        $id = $this->getValue('id', true, 'int');
        if (empty($id)) {
            $this->error('参数错误');
        }
        if ($res = $this->s_coupon->search(['id' => $id])) {
            $this->success($res);
        }
        $this->error();
    }

    public function singleVoucherCreateAction()
    {
        if (empty($this->uid)) {
            $this->error('非法访问');
        }
        $params = [];
        $coupon_value = $this->getValue('coupon_value', true, 'int');
        if (empty($coupon_value)) {
            $this->error('面额不能为空');
        }
        $params['coupon_value'] = $coupon_value;
        $use_condition = $this->getValue('use_condition', true, 'int');
        if (empty($use_condition)) {
            $this->error('使用条件不能为空');
        }
        $params['use_condition'] = $use_condition;
        $effective_time = $this->getValue('effective_time', true, 'int');
        if (empty($effective_time)) {
            $this->error("几日内可用不能为空");
        }
        $params['effective_time'] = $effective_time;
        $id = $this->getValue('id', false, 'int');
        if (!empty($id)) {
            $isUp = $this->s_coupon->search(['id' => $id, 'status' => 'N']);
            if (empty($isUp)) {
                $this->error('该券已发放，无法更改');
            }
            $params['id'] = $id;
        }
        if ($res = $this->s_coupon->singleVipVoucher($params)) {
            $this->success($res);
        }
        $this->error();
    }

    public function singleVoucherGrantAction()
    {
        $uid = $this->getValue('uid', true, 'int');
        $coupon_id = $this->getValue('coupon_id', true, 'int');
        $coupon_info = $this->s_coupon->search(['id' => $coupon_id]);
        if (empty($coupon_info)) {
            $this->error('券不存在');
        }
        $add = [];
        $add['uid'] = $uid;
        $add['type'] = '4';
        $add['coupon_id'] = $coupon_id;
        $add['num'] = $coupon_info['payment_amount'];
        $add['status'] = 'N';

        $today = date('Y-m-d');
        $startedAtTimestamp = strtotime($today . ' 00:00:00');
        $endedAtTimestamp = $startedAtTimestamp - 1 + ($coupon_info['effective_time'] + 1) * 86400;

        $add['stime'] = $startedAtTimestamp;
        $add['etime'] = $endedAtTimestamp;
      // 检验重复发放
        $is_exist = $this->s_coupon_receive->search(['uid' => $uid, 'coupon_id' => $coupon_id]);
        if ($is_exist) {
            $this->error('重复发放');
        }
        if ($this->s_coupon_receive->save($add)) {
            $this->success();
        }
        $this->error('单人代金券发放失败');
    }

    public function releaseVipCouponAction()
    {
        $couponId = $this->getValue('coupon_id', true, 'int');

        $isReleased = $this->s_coupon_receive->getCount(['coupon_id' => $couponId]) > 0;
        if ($isReleased) {
            return $this->error('该代金券已发放，请勿重复发放');
        }

        $coupon = $this->s_coupon->search(['id' => $couponId]);
        if (!$coupon) {
            return $this->error('未找到该代金券');
        }

        $currentLevel = $this->s_level->search(['name' => $coupon['vip_name']]);
        if (!$currentLevel) {
            return $this->error('未找到对应用户等级');
        }

        $creditRange = $this->s_level->getNextLevelScore($currentLevel['id']);
        $users = $this->s_user->searchAll(
            ['credit' => $creditRange],
            ['credit' => 'between']
        );

        $today = date('Y-m-d');
        $startedAtTimestamp = strtotime($today . ' 00:00:00');
        $endedAtTimestamp = $startedAtTimestamp - 1 + ($coupon['effective_time'] + 1) * 86400;

        $additionData = array_map(function ($item) use ($coupon, $startedAtTimestamp, $endedAtTimestamp) {
            return [
            'uid'       => $item['uid'],
            'type'      => $coupon['type'],
            'coupon_id' => $coupon['id'],
            'num'       => 1,
            'status'    => 'N',
            'stime'     => $startedAtTimestamp,
            'etime'     => $endedAtTimestamp,
            ];
        }, $users);

        $this->s_coupon_receive->saves($additionData)
        ? $this->success()
        : $this->error('代金券发放失败');
    }
}
